//
//  NSMAssetPickerController.m
//  NSMKit
//
//  Created by nsm on 2019/3/4.
//  Copyright © 2019 nani. All rights reserved.
//

#import "NSMAssetPickerController.h"
//#import "NSMKit.h"
#import "NSMAssetPickerCell.h"
//#import <YYKit.h>

static NSString * const kNormalCellReuseIdentifier = @"cell_normal";
static NSString * const kVideoCellReuseIdentifier = @"cell_video";
const CGFloat kToolBarHeight = 44.f;

@interface NSMAssetPickerController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *toolbarView;
@property (nonatomic, strong) NSArray<NSMAsset *> *mediaAssets;

@property(nonatomic, assign) BOOL isImagesAssetLoaded;
@property(nonatomic, assign) BOOL hasScrollToInitialPosition;
@end

@implementation NSMAssetPickerController

#pragma mark - lifeCycle
- (void)didInitialize {
    [super didInitialize];
    
    self.arrangedCount = 4;
    self.minimumSelectedCount = 0;
    self.maximumSelectedCount = 1;
    
    self.operationQueue = NSOperationQueue.new;
    self.operationQueue.maxConcurrentOperationCount = 3;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    CGRect rect = self.view.bounds;
    if (self.maximumSelectedCount > 1) {
        // 多选有工具条
        CGFloat barH = kToolBarHeight + self.view.nsm_safeAreaInsets.bottom;
        CGRect barRect = CGRectMake(0,
                                    rect.size.height-barH,
                                    rect.size.width,
                                    barH);
        if (!CGRectEqualToRect(self.toolbarView.frame, barRect)) {
            self.toolbarView.frame = barRect;
        }
        rect.size.height -= barH;
    } else {
        // 单选无工具条
        rect.size.height -= self.view.nsm_safeAreaInsets.bottom;
    }
    
    if (!CGRectEqualToRect(self.collectionView.frame, rect)) {
        self.collectionView.frame = rect;
    }
    
    // [self scrollToInitialPositionIfNeeded];
}

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 切换到异步
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.mediaAssets = self.assetsGroup.assets;
        self.isImagesAssetLoaded = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            // 刷新数据,默认滚动到底部,以后再优化
            //            self.collectionView.alpha = 0;
            [self.collectionView reloadData];
            //            dispatch_async(dispatch_get_main_queue(), ^{
            [self scrollToInitialPositionIfNeeded];
            //                [UIView animateWithDuration:0.5 animations:^{
            //                    self.collectionView.alpha = 1;
            //                }];
            //            });
            
            // [self.collectionView performBatchUpdates:NULL completion:^(BOOL finished) {
            //    [self scrollToInitialPositionIfNeeded];
            // }];
        });
    });
}

- (void)initSubviews {
    [super initSubviews];
    
    [self initCollectionView];
    // 工具条
    if (self.maximumSelectedCount > 1) {
        [self initToolbarView];
    }
}

- (void)initCollectionView {
    UICollectionViewFlowLayout *layout = UICollectionViewFlowLayout.new;
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumLineSpacing = 1;
    layout.minimumInteritemSpacing = 1;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:kScreenBounds
                                                          collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.whiteColor;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    _collectionView = collectionView;
    
    [collectionView registerClass:NSMAssetPickerCell.class forCellWithReuseIdentifier:kNormalCellReuseIdentifier];
    [collectionView registerClass:NSMAssetPickerCell.class forCellWithReuseIdentifier:kVideoCellReuseIdentifier];
}

- (void)initToolbarView {
    UIView *barView = UIView.new;
    barView.backgroundColor = RandomColor();
    [self.view addSubview:barView];
    _toolbarView = barView;
}

#pragma mark - setter/getter
- (void)setArrangedCount:(NSUInteger)arrangedCount {
    arrangedCount = MAX(arrangedCount, 1);
    _arrangedCount = arrangedCount;
}

- (CGSize)referenceItemSize {
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat w = (self.collectionView.width - flowLayout.minimumInteritemSpacing*(self.arrangedCount-1)) / self.arrangedCount;
    return CGSizeMake(w, w);
}

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private
- (void)scrollToInitialPositionIfNeeded {
    if (!(self.collectionView.canScroll &&
          self.collectionView.window &&
          self.isImagesAssetLoaded &&
          !self.hasScrollToInitialPosition)) {
        return;
    }
    [self.collectionView scrollToBottomAnimated:NO];
    self.hasScrollToInitialPosition = YES;
}

#pragma mark - UICollectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.mediaAssets.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self referenceItemSize];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSMAsset *asset = self.mediaAssets[indexPath.item];
    NSString *identifier;
    if (asset.asset.mediaType == PHAssetMediaTypeVideo)
        identifier = kVideoCellReuseIdentifier;
    else
        identifier = kNormalCellReuseIdentifier;
    
    NSMAssetPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [cell setAsset:asset];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    NSMAsset *asset = self.mediaAssets[indexPath.item];
    !self.didSelectItem?:self.didSelectItem(asset);
}

#pragma mark - action

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
